<template>
  <div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar
      class="app-nav-bar"
      title="文章详情"
      left-arrow
      @click-left="$router.back()"
    >
    </van-nav-bar>

    <div class="main-wrap">
      <!-- 加载中 -->
      <div class="loading-wrap">
        <van-loading color="#3296fa" vertical></van-loading>
      </div>
      <!-- 加载完成-文章详情 -->
      <div class="article-wrap">
        <h1 class="title">{{ article.title }}</h1>
        <van-cell center>
          <div slot="title" class="title">{{ article.aut_name }}</div>

          <div slot="label">{{ article.pubdate }}</div>
          <van-button
            round
            size="small"
            :type="article.is_followed ? 'default' : 'info'"
            :icon="article.is_followed ? '' : 'plus'"
            :loading="isFollowLoading"
            class="follow-btn"
            @click="onFollow"
            >{{ article.is_followed ? "已关注" : "关注" }}</van-button
          >
        </van-cell>
        <div
          class="markdown-body"
          v-html="article.content"
          ref="article-content"
        ></div>
        <!-- 评论列表 -->
        <comment-list
          :source="artilceId"
          :commentList="commentList"
          @total-count="totalCount"
        ></comment-list>
      </div>

      <!-- 加载失败 -->
      <div class="error-wrap">
        <van-icon name="failure"></van-icon>
        <p>该资源不存在或已删除</p>
      </div>

      <!-- 加载失败，其它未知错误，（例如网络原因或服务器抛异常） -->
      <div class="error-wrap">
        <van-icon name="failure"></van-icon>
        <p>内容加载失败</p>
        <van-button class="retry-btn">点击重试</van-button>
      </div>
    </div>

    <!-- 底部区域 -->
    <div class="acticle-bottom">
      <van-button
        class="comment-bnt"
        type="default"
        round
        size="small"
        @click="isPostShow = true"
        >写评论</van-button
      >
      <van-icon name="comment-o" :info="total_count" color="#777"></van-icon>
      <van-icon
        :name="article.is_collected ? 'star' : 'star-o'"
        :color="article.is_collected ? 'orange' : '#777'"
        :loading="isCollectLoading"
        @click="onCollect"
      ></van-icon>
      <van-icon
        :name="article.attitude === 1 ? 'good-job' : 'good-job-o'"
        :color="article.attitude === 1 ? 'hotpink' : '#777'"
        @click="onLike"
      ></van-icon>
      <van-icon name="share" color="#777"></van-icon>
    </div>

    <!-- 发布评论 -->
    <van-popup v-model="isPostShow" position="bottom">
      <Post-comment
        :target="article.art_id"
        :artilceId="artilceId"
        @post-success="postSuccess"
      ></Post-comment>
    </van-popup>
  </div>
</template>

<script>
// 在组件中获取动态路由参数：
//  方式一： this.$route.params.xxx
// 方式二： props  传参， 推荐
import {
  getArticleById,
  deleteFollow,
  addFollow,
  deleteCollect,
  addCollect,
  addLike,
  deleteLike,
} from "@/api/article";
import { ImagePreview } from "vant";
import { mapState } from "vuex";
import CommentList from "./components/comment-list";
import PostComment from "./components/post-comment";

export default {
  name: "ArticleIndex",
  props: {
    artilceId: {
      type: [String, Number, Object],
      required: true,
    },
  },
  computed: {
    ...mapState(["user"]),
  },
  components: {
    CommentList,
    PostComment,
  },
  data() {
    return {
      article: {}, // 文章数据对象
      isFollowLoading: false, // 关注用户按钮的状态
      isCollectLoading: false,
      isPostShow: false, // 控制发布评论的显示
      total_count: 0,
      commentList: [],
    };
  },
  created() {
    this.loadArticle();
  },
  methods: {
    async loadArticle() {
      const { data } = await getArticleById(this.artilceId);
      this.article = data.data;

      // 数据改变影响视图更新（DOM数据）不是立即的
      // 所以如果需要在修改数据之后马上操作被改数据影响的视图DOM，需要把这个代码放到$nextTick中
      // 得到所有的img标签，给img注册点击事件
      this.$nextTick(() => {
        this.handlePerviewImage();
      });
    },
    totalCount(count) {
      this.total_count = count;
    },
    // 关注和不关注
    async onFollow() {
      if (this.user) {
        this.isFollowLoading = true;
        if (this.article.is_followed) {
          const { data } = await deleteFollow(this.article.aut_id);
        } else {
          const { data } = await addFollow(this.article.aut_id);
        }
        this.article.is_followed = !this.article.is_followed;
        this.isFollowLoading = false;
      } else {
        this.$toast.success("请登录");
      }
    },
    postSuccess(data) {
      this.isPostShow = false;
      this.commentList.unshift(data.new_obj);
    },
    // 收藏、不收藏
    async onCollect() {
      if (this.user) {
        this.$toast.loading({
          message: "操作中...",
          forbidClick: true, // 禁止背景点击
        });
        this.isCollectLoading = true;
        if (this.article.is_collected) {
          const { data } = await deleteCollect(this.artilceId);
        } else {
          const { data } = await addCollect(this.artilceId);
        }
        this.article.is_collected = !this.article.is_collected;
        this.isCollectLoading = false;

        this.$toast.success(
          `${this.article.is_collected ? "" : "取消"}收藏成功`
        );
      } else {
        this.$toast.success("请登录");
      }
    },
    async onLike() {
      if (this.user) {
        this.$toast.loading({
          message: "操作中...",
          forbidClick: true, // 禁止背景点击
        });
        if (this.article.attitude === 1) {
          const { data } = await deleteLike(this.artilceId);
          this.article.attitude = -1;
        } else {
          const { data } = await addLike(this.artilceId);
          this.article.attitude = 1;
        }
        this.$toast.success(
          `${this.article.attitude === 1 ? "" : "取消"}点赞成功`
        );
      } else {
        this.$toast.success("请登录");
      }
    },
    handlePerviewImage() {
      // 获取文章内容DOM容器
      const articleContent = this.$refs["article-content"];
      const imgs = articleContent.querySelectorAll("img");
      const imgPaths = [];
      imgs.forEach((img, index) => {
        imgPaths.push(img.src);
        img.onclick = function () {
          ImagePreview({
            images: imgPaths,
            startPosition: index,
          });
        };
      });
    },
  },
};
</script>

<style scoped lang="less">
.article-container {
  padding-bottom: 51px;
}
.title {
  font-size: 20px;
  color: #3a3a3a;
  padding: 14px;
}
.follow-btn {
  width: 85px;
  height: 29px;
}

.markdown-body {
  padding: 14px;
  background-color: #fff;
  font-size: 16px;
}
.markdown-body /deep/ img {
  width: 100%;
}
.acticle-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  height: 50px;
  display: flex;
  align-items: center;
  background-color: #fff;
  width: 100%;
  border-top: 1px solid #ddd;
  .comment-bnt {
    width: 140px;
    margin: 0 20px;
  }
  .van-icon {
    flex: 1;
    text-align: center;
    /deep/ .van-info {
      right: 10px;
    }
  }
}
</style>
